package com.qianmi.cloud.dialogue;

import com.qianmi.cloud.vo.Principal;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

/**
 * @Description
 * @Date 2022-02-16 15:20
 * @Created by cai chao
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 获取用户
     *
     * @return PigxUser
     * <p>
     */
    public OAuth2AuthenticationDetails getDetail() {
        Authentication authentication = getAuthentication();
        Object details = authentication.getDetails();
        if (details instanceof OAuth2AuthenticationDetails) {
            return (OAuth2AuthenticationDetails) details;
        }
        return null;
    }

    /**
     * 获取用户
     */
    public Principal getUser() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof Principal) {
            return (Principal) principal;
        }
        return null;
    }
}
